from fastapi import APIRouter, HTTPException
from typing import List

from app.crud.simulation_result_total import (
    create_total,
    list_totals,
    get_total_by_id,
    get_simulation_results_by_total_id, delete_total_by_id
)
from app.schemas.simulation_result_total import (
    SimulationResultTotalOut,
    SimulationResultTotalCreate,
    SimulationResultTotalOutDetail,
)
from app.utils.Result import Result  # 你这个是统一响应封装

router = APIRouter()

@router.get(
    "/",
    response_model=Result[List[SimulationResultTotalOut]],
    summary="获取所有汇总结果",
    description="查询所有 simulation_result_total 记录。",
)
async def get_totals():
    totals = await list_totals()
    return Result.ok(data=totals)

@router.get(
    "/{total_id}/results",
    response_model=Result[SimulationResultTotalOutDetail],
    summary="获取汇总对应的详细结果",
    description="根据 simulation_result_total 的 ID 获取其关联的 simulation_result 详细列表。",
)
async def get_result_details_by_total(total_id: int):
    details = await get_simulation_results_by_total_id(total_id)
    return Result.ok(data=details)

@router.get(
    "/{total_id}",
    response_model=Result[SimulationResultTotalOut],
    summary="获取指定汇总结果",
    description="根据 simulation_result_total 的 ID 查询单个汇总记录。",
)
async def get_total(total_id: int):
    total = await get_total_by_id(total_id)
    if not total:
        raise HTTPException(status_code=404, detail="汇总结果不存在")
    return Result.ok(data=total)

@router.post(
    "/",
    response_model=Result[SimulationResultTotalOut],
    summary="创建新的汇总结果",
    description="创建一个新的 simulation_result_total 汇总记录。",
)
async def create_simulation_total(total_in: SimulationResultTotalCreate):
    total = await create_total(total_in)
    return Result.ok(data=total)

@router.delete(
    "/{total_id}",
    response_model=Result[str],
    summary="根据ID删除汇总结果",
    description="根据 simulation_result_total 的 ID 删除对应的汇总记录及其关联的详细结果。"
)
async def delete_simulation_total(total_id: int):
    deleted_count = await delete_total_by_id(total_id)
    if deleted_count == 0:
        return Result.error(code=500, msg="删除失败")
    return Result.ok(msg="删除成功")
